import glob
import os
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
import keyboard

def create_window(parent):
    def find_png_files(directory):
        png_files = glob.glob(os.path.join(directory, '**', '*.png'), recursive=True)
        return png_files

    # 创建窗口
    root = tk.Toplevel(parent)
    root.title("序列帧图片合并器")
    root.config(bg="grey")
    root.geometry("1300x1000+0+0")

    # background_image = Image.open("D:/Users/admin/Downloads/composite/body_output/50001_ATTACK_0/0.png")
    # background_photo = ImageTk.PhotoImage(background_image)
    # canvas.
    # 暂停修改--将index保持不动，一直重复刷同一帧

    global offX, offY
    offX = 60
    offY = 50
    tk.Label(root,text="请输入文件夹路径", bg='green').place(x=offX, y=2)
    tk.Label(root,text="勾选复选框启用锚点修改功能", bg='green').place(x=offX, y=20)

    check_var = tk.IntVar()
    check_var1 = tk.IntVar()
    check_var2 = tk.IntVar()
    check_var3 = tk.IntVar()

    def check_status():
        if check_var.get():
            return 'on'
        else:
            return 'off'

    def check_status1():
        if check_var1.get():
            return 'on'
        else:
            return 'off'

    def check_status2():
        if check_var2.get():
            return 'on'
        else:
            return 'off'

    # 输入框一
    entry_var = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var)
    check_anchor = tk.Checkbutton(root, variable=check_var).place(x=offX +150, y=offY - 3)
    entry_path.place(x=offX, y=offY)

    tk.Label(root, text="请输入模型ID或模型ID具体动作", bg='green').place(x=offX+600, y=offY -40)
    entry_role = tk.StringVar()
    entry_rolename = tk.Entry(root, textvariable=entry_role)
    entry_rolename.place(x=offX+600, y=offY)
    # 输入框二
    entry_var1 = tk.StringVar()
    entry_path1 = tk.Entry(root, textvariable=entry_var1)
    check_anchor1 = tk.Checkbutton(root, variable=check_var1).place(x=offX + 350, y=offY - 3)
    entry_path1.place(x=offX + 200, y=offY)

    tk.Label(root,text="请输入技能ID", bg='green').place(x=offX + 800, y=offY -40)
    entry_skill = tk.StringVar()
    entry_skillname = tk.Entry(root, textvariable=entry_skill)
    entry_skillname.place(x=offX + 800, y=offY)
    # 输入框三
    entry_var2 = tk.StringVar()
    entry_path2 = tk.Entry(root, textvariable=entry_var2)
    check_anchor2 = tk.Checkbutton(root, variable=check_var2).place(x=offX + 550, y=offY - 3)
    entry_path2.place(x=offX + 400, y=offY)

    tk.Label(root,text="请输入武器ID或武器ID具体动作", bg='green').place(x=offX + 1000, y=offY -40)
    entry_wuqi = tk.StringVar()
    entry_wuqiname = tk.Entry(root, textvariable=entry_wuqi)
    entry_wuqiname.place(x=offX + 1000, y=offY)

    # 切换指定ID角色
    def change_role():
        global role_button, role_name, directory_type, cur_frame_index
        role_name = entry_role.get()
        directory_type = []
        # index = 0
        for item in all_directory_type:
            for name in item:
                if role_name in name:
                    directory_type.append(name)
                    # cur_directory_type_index = index
                    # return
            # index+=1
        load_images_from_directory1()
        cur_frame_index = 0

    # 切换指定ID技能
    def change_skill():
        global skill_button, skill_name, directory_type1, cur_frame_index
        skill_name = entry_skill.get()
        directory_type1 = []
        # index = 0
        for item in all_directory_type1:
            for name in item:
                if skill_name in name:
                    # cur_directory_type_index1 = index
                    directory_type1.append(name)
                    # return
            # index+=1
        load_images_from_directory2()
        cur_frame_index = 0

    # 切换指定ID武器
    def change_wuqi():
        global wuqi_button, wuqi_name, directory_type2, cur_frame_index
        wuqi_name = entry_wuqi.get()
        directory_type2 = []
        # index = 0
        for item in all_directory_type2:
            for name in item:
                if wuqi_name in name:
                    # cur_directory_type_index2 = index
                    directory_type2.append(name)
                    # return
            # index+=1
        load_images_from_directory3()
        cur_frame_index = 0

    role_button = tk.Button(root, text="加载指定ID模型", command=change_role, bg='skyblue').place(x=offX+600, y=offY + 40)
    skill_button = tk.Button(root, text="加载指定ID技能", command=change_skill, bg='red').place(x=offX+800,
                                                                                                y=offY + 40)
    wuqi_name = tk.Button(root, text="加载指定ID武器", command=change_wuqi, bg='orange').place(x=offX + 1000,
                                                                                               y=offY + 40)

    global image_frames, image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index, input_x, input_y, input_x_value, input_y_value,change_hierarchys
    input_x = 0
    input_y = 0
    input_x_value = 0
    input_y_value = 0
    image_frames = []
    image_frames1 = []
    image_frames2 = []
    image_frames3 = []
    cur_directory_type_index = 0
    cur_frame_index = 0
    change_hierarchys=True

    global speed
    speed = 100

    # 从目录加载图片
    def load_images_from_directory():
        global image_frames, image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index
        image_paths = []
        for i, d in enumerate(all_directory_type[cur_directory_type_index]):
            image_paths.extend(find_png_files(image_frames_path + "/" + d))

        if not image_paths:
            messagebox.showerror("Error", "目录一没有图片文件")

        if image_frames_path1 != '':
            image_paths1 = []
            for i, d in enumerate(all_directory_type1[cur_directory_type_index1]):
                image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
            image_frames1 = [Image.open(path) for path in image_paths1]

        if image_frames_path2 != '':
            image_paths2 = []
            for i, d in enumerate(all_directory_type2[cur_directory_type_index2]):
                image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
            image_frames2 = [Image.open(path) for path in image_paths2]

        cur_frame_index = 0
        image_frames = [Image.open(path) for path in image_paths]
        reset_window()

        # 从目录加载指定动作图片

    def load_images_from_directory1():
        global image_frames, cur_frame_index, cur_directory_type_index, directory_type
        image_paths = []
        for i, d in enumerate(directory_type):
            image_paths.extend(find_png_files(image_frames_path + "/" + d))
        if not image_paths:
            messagebox.showerror("Error", "目录一没有图片文件")
        cur_frame_index = 0
        image_frames = [Image.open(path) for path in image_paths]
        reset_window()

    def load_images_from_directory2():
        global image_frames1, cur_frame_index, directory_type1
        if image_frames_path1 != '':
            image_paths1 = []
            for i, d in enumerate(directory_type1):
                image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
            image_frames1 = [Image.open(path) for path in image_paths1]
            cur_frame_index = 0
            reset_window()

    def load_images_from_directory3():
        global image_frames2, cur_frame_index, directory_type2
        if image_frames_path2 != '':
            image_paths2 = []
            for i, d in enumerate(directory_type2):
                image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
            image_frames2 = [Image.open(path) for path in image_paths2]
            cur_frame_index = 0
            reset_window()

    # 获取输入路径
    def get_input_path():
        global image_frames, last_button, next_button, image_frames_path, image_frames_path1, image_frames_output_path, image_frames_output_path1
        global all_directory_type, all_directory_type1, cur_directory_type_index, cur_directory_type_index1
        # 路径一
        all_directory_type = []
        cur_directory_type_index = 0
        image_frames_path = entry_var.get().replace("\\", "/")
        if image_frames_path != '':
            image_frames_output_path = image_frames_path + "_output"
            all_directory = [d for d in os.listdir(image_frames_path) if
                             os.path.isdir(os.path.join(image_frames_path, d))]
            dir_name = ""
            for i, d in enumerate(all_directory):
                net_dir_name = os.path.basename(d)
                if dir_name.split("_")[0] == net_dir_name.split("_")[0]:
                    all_directory_type[-1].append(net_dir_name)
                else:
                    dir_name = net_dir_name
                    all_directory_type.append([dir_name])

        if not all_directory_type:
            messagebox.showerror("Error", "路径一没有目录")
            # return
        # 路径二
        all_directory_type1 = []
        cur_directory_type_index1 = 0
        image_frames_path1 = entry_var1.get().replace("\\", "/")
        if image_frames_path1 != '':
            image_frames_output_path1 = image_frames_path1 + "_output"
            all_directory1 = [d for d in os.listdir(image_frames_path1) if
                              os.path.isdir(os.path.join(image_frames_path1, d))]
            dir_name1 = ""
            for i, d in enumerate(all_directory1):
                net_dir_name1 = os.path.basename(d)
                if dir_name1.split("_")[0] == net_dir_name1.split("_")[0]:
                    all_directory_type1[-1].append(net_dir_name1)
                else:
                    dir_name1 = net_dir_name1
                    all_directory_type1.append([dir_name1])

        # 路径三
        global all_directory_type2, cur_directory_type_index2, image_frames_path2, image_frames_output_path2
        all_directory_type2 = []
        cur_directory_type_index2 = 0
        image_frames_path2 = entry_var2.get().replace("\\", "/")
        if image_frames_path2 != '':
            image_frames_output_path2 = image_frames_path2 + "_output"
            all_directory2 = [d for d in os.listdir(image_frames_path2) if
                              os.path.isdir(os.path.join(image_frames_path2, d))]
            dir_name2 = ""
            for i, d in enumerate(all_directory2):
                net_dir_name2 = os.path.basename(d)
                if dir_name2.split("_")[0] == net_dir_name2.split("_")[0]:
                    all_directory_type2[-1].append(net_dir_name2)
                else:
                    dir_name2 = net_dir_name2
                    all_directory_type2.append([dir_name2])

        load_images_from_directory()

    get_input_button = tk.Button(root, text="加载图片", command=get_input_path, bg='skyblue')
    get_input_button.place(x=offX + 200, y=offY - 40)

    def btn_last_directory():
        global cur_directory_type_index, cur_directory_type_index1
        if cur_directory_type_index <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index -= 1
        load_images_from_directory()

    def btn_next_directory():
        global cur_directory_type_index
        if cur_directory_type_index >= len(all_directory_type) - 1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index += 1
        load_images_from_directory()

    last_button = tk.Button(root, text="上一个", command=btn_last_directory)
    last_button.place(x=offX + 10, y=offY + 40)
    next_button = tk.Button(root, text="下一个", command=btn_next_directory)
    next_button.place(x=offX + 90, y=offY + 40)

    # 按钮，上下切换图片资源二
    global last_button1, next_button1

    def btn_last_directory1():
        global cur_directory_type_index1
        if cur_directory_type_index1 <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index1 -= 1
        load_images_from_directory()

    def btn_next_directory1():
        global cur_directory_type_index1
        if cur_directory_type_index1 >= len(all_directory_type1) - 1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index1 += 1
        load_images_from_directory()

    last_button1 = tk.Button(root, text="上一个", command=btn_last_directory1)
    last_button1.place(x=offX + 210, y=offY + 40)
    next_button1 = tk.Button(root, text="下一个", command=btn_next_directory1)
    next_button1.place(x=offX + 290, y=offY + 40)

    # 按钮，上下切换图片资源三
    global last_button2, next_button2

    def btn_last_directory2():
        global cur_directory_type_index2
        if cur_directory_type_index2 <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index2 -= 1
        load_images_from_directory()

    def btn_next_directory2():
        global cur_directory_type_index2
        if cur_directory_type_index2 >= len(all_directory_type2) - 1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index2 += 1
        load_images_from_directory()

    last_button1 = tk.Button(root, text="上一个", command=btn_last_directory2)
    last_button1.place(x=offX + 410, y=offY + 40)
    next_button1 = tk.Button(root, text="下一个", command=btn_next_directory2)
    next_button1.place(x=offX + 490, y=offY + 40)

    # 图像绘制位置坐标
    canvas = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas.place(x=offX + 70, y=offY + 100)

    # 保存图片
    def save_canvas_as_image():
        global image_frames, image_frames1, image_name, change_hierarchys
        ind = 0
        # 确保 change_hierarchys 被定义
        if 'change_hierarchys' not in globals():
            print("Error: change_hierarchys 未定义")
            return
        image_frame = image_frames[0]
        length = len(image_frames) - 1
        # length2 = len(image_frames1) - 1
        # lists = []
        # if(length > length2):
        #     lists = image_frames
        # else :
        #     lists = image_frames1

        for i, img in enumerate(image_frames1):
            # 拿到主图
            if (i > length):
                image_frame = image_frames[length]
            else:
                image_frame = image_frames[i]

            # if( i > length2):
            #     image_frame2 = image_frames1[length2]
            # else:
            #     image_frame2 = image_frames1[i]
            # 获取两张图片的尺寸
            width1, height1 = image_frame.size
            width2, height2 = img.size

            # 找到最大的宽度和高度
            max_width = max(width1, width2)
            max_height = max(height1, height2)

            # 创建一个与较大图片尺寸相同的透明背景
            new_img1 = Image.new("RGBA", (max_width, max_height), (255, 255, 255, 0))
            new_img2 = Image.new("RGBA", (max_width, max_height), (255, 255, 255, 0))

            # 将原图粘贴到新创建的透明背景上，保持居中
            new_img1.paste(image_frame, ((max_width - width1) // 2, (max_height - height1) // 2))
            new_img2.paste(img, ((max_width - width2) // 2, (max_height - height2) // 2))

            # 叠加两张图片，保留透明部分
            if (change_hierarchys):
                final_image = Image.alpha_composite(new_img1, new_img2)
            else:
                final_image = Image.alpha_composite(new_img2, new_img1)

            # 保存为文件
            file_name = image_name.split("/")[1]
            Path = image_frames_output_path + "/" + file_name + "/" + str(ind) + ".png"
            if not os.path.exists(os.path.dirname(Path)):
                os.makedirs(os.path.dirname(Path))
            final_image.save(Path)
            print("保存至"+Path)
            ind += 1

    save_button = tk.Button(root, text="合并图像", command=save_canvas_as_image, bg="skyblue").place(x=offX + 450,
                                                                                                     y=offY - 40)

    # 调整量输入框
    entry_var_change = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_change, width=5)
    entry_path.place(x=offX + 300, y=offY - 37)

    def save_change_input_values():
        global input_x_value, input_y_value
        input_x_value = entry_var_change.get()
        input_y_value = entry_var_change.get()
        print("x"+input_x_value)
        print("y" + input_y_value)

    save_change_input_value = tk.Button(root, text="调整", command=save_change_input_values, bg="skyblue").place(
        x=offX + 350, y=offY - 40)

    #change_hierarchys = True
    tk.Label(root,text="路径一置底", bg='green').place(x=offX, y=offY + 190)

    def change_hierarchy():
        global change_hierarchys, hierarchy_button
        change_hierarchys = not change_hierarchys
        if (change_hierarchys):
            tk.Label(text="路径一置底", bg='green').place(x=offX, y=offY + 190)
        else:
            tk.Label(text="路径二置底", bg='orange').place(x=offX, y=offY + 190)

    hierarchy_button = tk.Button(root, text="层级切换", command=change_hierarchy).place(x=offX, y=180)

    # 重置窗口
    def reset_window():
        global image_max_width, image_max_height, canvas_width, canvas_height, center_x, center_y, cur_frame_index
        image_max_width = 0
        image_max_height = 0
        canvas_width = 1000
        canvas_height = 1000
        center_x = 0
        center_y = 0
        cur_frame_index = 0
        for i, img in enumerate(image_frames):
            image_max_width = max(image_max_width, img.width)
            image_max_height = max(image_max_height, img.height)

        root_width = max(canvas_width, image_max_width)
        root_height = max(canvas_height, image_max_height)
        # 处理大图
        root.geometry(f"{root_width}x{root_height}")
        canvans_width = max(800, image_max_width)
        canvans_height = max(800, image_max_height)
        canvas.config(width=canvans_width, height=canvans_width)
        center_x = canvans_width / 2
        center_y = canvans_height / 2

    # 刷新序列帧动画
    def update_frame():
        global photo_image, photo_image1, photo_image2, photo_image3, cur_frame_index, root_after, path_index1, image_name
        global input_x, input_y
        if image_frames:
            # 目录一
            if cur_frame_index >= len(image_frames):
                path_index = len(image_frames) - 1
                image_frame = image_frames[path_index]
                photo_image = ImageTk.PhotoImage(image_frame)
            else:
                image_frame = image_frames[cur_frame_index]
                photo_image = ImageTk.PhotoImage(image_frame)
            # 目录二
            if image_frames_path1 != '':
                if cur_frame_index >= len(image_frames1):
                    path_index1 = len(image_frames1) - 1
                    image_frame1 = image_frames1[path_index1]
                    photo_image1 = ImageTk.PhotoImage(image_frame1)
                else:
                    image_frame1 = image_frames1[cur_frame_index]
                    photo_image1 = ImageTk.PhotoImage(image_frame1)
            # 目录三
            if image_frames_path2 != '':
                if cur_frame_index >= len(image_frames2):
                    path_index2 = len(image_frames2) - 1
                    image_frame2 = image_frames2[path_index2]
                    photo_image2 = ImageTk.PhotoImage(image_frame2)
                else:
                    image_frame2 = image_frames2[cur_frame_index]
                    photo_image2 = ImageTk.PhotoImage(image_frame2)

            canvas.delete("all")  # 清除之前的图像
            canvas.create_rectangle(center_x - image_frame.width / 2, center_y - image_frame.height / 2,
                                    center_x + image_frame.width / 2, center_y + image_frame.height / 2, fill="white",
                                    outline="black")
            if check_status() == 'on':
                canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER,
                                    image=photo_image)
            else:
                canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image)
            if image_frames_path1 != '':
                if check_status1() == 'on':
                    canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER,
                                        image=photo_image1)
                else:
                    canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image1)
            if image_frames_path2 != '':
                if check_status2() == 'on':
                    canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER,
                                        image=photo_image2)
                else:
                    canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image2)

            canvas.create_line(0, center_y, canvas_width, center_y, fill="red", width=1)
            canvas.create_line(center_x, 0, center_x, canvas_height, fill="red", width=1)

            # 显示当前正在播放的人物，技能和武器动画名称
            image_name = image_frame.filename.replace("\\", "/").replace(image_frames_path, "")
            root.title("人物" + image_name)
            length = len(image_frames)
            if image_frames_path1 != '':
                image_name1 = image_frame1.filename.replace("\\", "/").replace(image_frames_path1, "")
                root.title("人物" + image_name + "   技能" + image_name1)
                length = max(len(image_frames), len(image_frames1))
            if image_frames_path2 != '':
                image_name2 = image_frame2.filename.replace("\\", "/").replace(image_frames_path2, "")
                root.title("人物" + image_name + "   技能" + image_name1 + "   武器" + image_name2)
                length = max(len(image_frames), len(image_frames1), len(image_frames2))

            cur_frame_index = (cur_frame_index + 1) % length  # 循环显示

        root_after = root.after(speed, update_frame)  # 每100毫秒更新一次

    # 移动帧动画
    def on_key_event(event):
        global input_x, input_y, input_x_value, input_y_value
        if keyboard.is_pressed('up'):  # 检查是否按下了 '' 键
            input_y -= int(input_y_value)
        if keyboard.is_pressed('down'):
            input_y += int(input_y_value)
        if keyboard.is_pressed('left'):
            input_x -= int(input_x_value)
        if keyboard.is_pressed('right'):
            input_x += int(input_x_value)
            # input_x += input_x
            # print("检测到 right 键！::" + str(input_x))
            # print(f"Key {event.name} was pressed")

    # 注册一个键盘事件
    keyboard.on_press(on_key_event)

    update_frame()



